'use client'

import React, { useEffect, useRef } from 'react'
import * as THREE from 'three'
import { EmergencyEvent, EmergencySeverity, EmergencyStatus } from '@/lib/emergencyEvents'

interface EmergencyMarkerProps {
  emergency: EmergencyEvent
  scene: THREE.Scene
  onMarkerClick?: (emergency: EmergencyEvent) => void
}

// 根据紧急程度获取颜色
const getSeverityColor = (severity: EmergencySeverity): string => {
  switch (severity) {
    case EmergencySeverity.CRITICAL:
      return '#FF0000' // 红色
    case EmergencySeverity.HIGH:
      return '#FF4500' // 橙红色
    case EmergencySeverity.MEDIUM:
      return '#FFA500' // 橙色
    case EmergencySeverity.LOW:
      return '#FFCC00' // 黄色
    default:
      return '#FF0000'
  }
}

// 根据状态获取不透明度
const getStatusOpacity = (status: EmergencyStatus): number => {
  switch (status) {
    case EmergencyStatus.ACTIVE:
      return 1.0
    case EmergencyStatus.RESPONDING:
      return 0.8
    case EmergencyStatus.CONTAINED:
      return 0.6
    case EmergencyStatus.RESOLVED:
      return 0.3
    default:
      return 1.0
  }
}

export const EmergencyMarker: React.FC<EmergencyMarkerProps> = ({ emergency, scene, onMarkerClick }) => {
  const markerRef = useRef<THREE.Group | null>(null)
  const animationRef = useRef<number | null>(null)
  const pulseRef = useRef<THREE.Mesh | null>(null)
  const textRef = useRef<THREE.Mesh | null>(null)
  const iconRef = useRef<THREE.Mesh | null>(null)
  
  // 清理函数
  const cleanup = () => {
    if (markerRef.current) {
      scene.remove(markerRef.current)
      markerRef.current = null
    }
    
    if (animationRef.current !== null) {
      cancelAnimationFrame(animationRef.current)
      animationRef.current = null
    }
  }
  
  // 创建紧急事件标记
  useEffect(() => {
    if (!scene) return cleanup
    
    // 创建标记组
    const group = new THREE.Group()
    group.name = `emergency-${emergency.id}`
    
    // 获取颜色和不透明度
    const color = emergency.visualEffect?.color || getSeverityColor(emergency.severity)
    const opacity = getStatusOpacity(emergency.status)
    const scale = emergency.visualEffect?.scale || 1.0
    const pulseRate = emergency.visualEffect?.pulseRate || 1.0
    
    // 创建基础圆柱体
    const cylinderGeometry = new THREE.CylinderGeometry(0.5, 0.5, 0.2, 32)
    const cylinderMaterial = new THREE.MeshBasicMaterial({
      color: new THREE.Color(color),
      transparent: true,
      opacity: opacity * 0.8
    })
    const cylinder = new THREE.Mesh(cylinderGeometry, cylinderMaterial)
    cylinder.position.y = 0.1
    cylinder.scale.set(scale, scale, scale)
    group.add(cylinder)
    
    // 创建脉冲圆环
    const ringGeometry = new THREE.RingGeometry(0.6, 0.8, 32)
    const ringMaterial = new THREE.MeshBasicMaterial({
      color: new THREE.Color(color),
      transparent: true,
      opacity: opacity * 0.6,
      side: THREE.DoubleSide
    })
    const ring = new THREE.Mesh(ringGeometry, ringMaterial)
    ring.rotation.x = -Math.PI / 2 // 水平放置
    ring.position.y = 0.05
    pulseRef.current = ring
    group.add(ring)
    
    // 创建图标（简单的几何体表示不同类型的紧急事件）
    let iconGeometry
    
    switch (emergency.type) {
      case 'fire':
        // 火焰形状（简化为锥体）
        iconGeometry = new THREE.ConeGeometry(0.2, 0.4, 8)
        break
      case 'medical':
        // 医疗十字（简化为立方体）
        iconGeometry = new THREE.BoxGeometry(0.3, 0.3, 0.1)
        break
      case 'security':
        // 安全盾牌（简化为半球）
        iconGeometry = new THREE.SphereGeometry(0.2, 16, 8, 0, Math.PI * 2, 0, Math.PI / 2)
        break
      case 'infrastructure':
        // 基础设施（简化为圆环）
        iconGeometry = new THREE.TorusGeometry(0.15, 0.05, 8, 16)
        break
      case 'crowd':
        // 人群（简化为多个小球）
        iconGeometry = new THREE.SphereGeometry(0.1, 8, 8)
        break
      default:
        // 默认为球体
        iconGeometry = new THREE.SphereGeometry(0.15, 16, 16)
    }
    
    const iconMaterial = new THREE.MeshBasicMaterial({
      color: new THREE.Color('#FFFFFF'),
      transparent: true,
      opacity: opacity
    })
    const icon = new THREE.Mesh(iconGeometry, iconMaterial)
    icon.position.y = 0.3
    iconRef.current = icon
    group.add(icon)
    
    // 添加文本标签（使用THREE.TextGeometry需要额外加载字体，这里简化为平面）
    const textPlaneGeometry = new THREE.PlaneGeometry(1, 0.3)
    const canvas = document.createElement('canvas')
    canvas.width = 256
    canvas.height = 64
    const context = canvas.getContext('2d')
    if (context) {
      context.fillStyle = '#000000'
      context.fillRect(0, 0, 256, 64)
      context.fillStyle = '#FFFFFF'
      context.font = 'bold 24px Arial'
      context.textAlign = 'center'
      context.textBaseline = 'middle'
      context.fillText(emergency.title, 128, 32)
      
      const texture = new THREE.CanvasTexture(canvas)
      const textMaterial = new THREE.MeshBasicMaterial({
        map: texture,
        transparent: true,
        opacity: opacity
      })
      const textPlane = new THREE.Mesh(textPlaneGeometry, textMaterial)
      textPlane.position.y = 0.6
      textPlane.rotation.x = -Math.PI / 4 // 倾斜一点，便于阅读
      textRef.current = textPlane
      group.add(textPlane)
    }
    
    // 添加影响区域指示器（如果有指定影响半径）
    if (emergency.location.areaRadius) {
      const areaGeometry = new THREE.CircleGeometry(emergency.location.areaRadius / 100, 32) // 缩放比例
      const areaMaterial = new THREE.MeshBasicMaterial({
        color: new THREE.Color(color),
        transparent: true,
        opacity: opacity * 0.2,
        side: THREE.DoubleSide
      })
      const area = new THREE.Mesh(areaGeometry, areaMaterial)
      area.rotation.x = -Math.PI / 2 // 水平放置
      area.position.y = 0.02
      group.add(area)
    }
    
    // 添加点击事件
    group.userData = { emergency, isEmergencyMarker: true }
    
    // 定位到地图上的位置
    const [lng, lat] = emergency.location.coordinates
    // 注意：这里假设有一个坐标转换函数，实际实现需要与地图组件对接
    // 暂时使用简单的坐标映射
    group.position.set(lng * 100, 0, lat * 100) // 简化的坐标转换
    
    // 添加到场景
    scene.add(group)
    markerRef.current = group
    
    // 动画效果
    const animate = () => {
      if (!pulseRef.current || !markerRef.current) return
      
      // 脉冲效果
      const time = Date.now() * 0.001
      const pulse = Math.sin(time * pulseRate) * 0.5 + 0.5
      
      if (pulseRef.current.material instanceof THREE.MeshBasicMaterial) {
        pulseRef.current.material.opacity = pulse * opacity * 0.6
      }
      
      if (iconRef.current && iconRef.current.material instanceof THREE.MeshBasicMaterial) {
        iconRef.current.scale.set(1 + pulse * 0.2, 1 + pulse * 0.2, 1 + pulse * 0.2)
      }
      
      // 根据事件状态旋转
      if (emergency.status === EmergencyStatus.ACTIVE) {
        group.rotation.y += 0.01
      }
      
      animationRef.current = requestAnimationFrame(animate)
    }
    
    animate()
    
    return cleanup
  }, [emergency, scene, onMarkerClick])
  
  // 当紧急事件状态变化时更新视觉效果
  useEffect(() => {
    if (!markerRef.current) return
    
    const opacity = getStatusOpacity(emergency.status)
    const color = emergency.visualEffect?.color || getSeverityColor(emergency.severity)
    
    // 更新所有材质
    markerRef.current.traverse((child) => {
      if (child instanceof THREE.Mesh && child.material instanceof THREE.MeshBasicMaterial) {
        if (child === pulseRef.current) {
          child.material.opacity = opacity * 0.6
        } else if (child === iconRef.current) {
          child.material.opacity = opacity
        } else if (child === textRef.current) {
          child.material.opacity = opacity
        } else {
          child.material.opacity = opacity * 0.8
          child.material.color.set(color)
        }
      }
    })
    
  }, [emergency.status, emergency.severity])
  
  return null // 这是一个纯3D组件，不渲染DOM
}

export default EmergencyMarker